package visiopuce.ui.providers;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;

import visiopuce.objets.Analyse;
import visiopuce.objets.Cotation;
import visiopuce.objets.Prelevement;
import visiopuce.service.AnalyseServiceImpl;
import visiopuce.service.PrelevementServiceImpl;

public class CotationComboEditingSupport extends EditingSupport {

	private final TableViewer viewer;
	private final ComboBoxCellEditor editor;
	private String[] listeCombo;

	public CotationComboEditingSupport(TableViewer viewer, int idPersonne) {
		super(viewer);
		this.viewer = viewer;

		List<String> liste = new ArrayList<String>();
		List<Prelevement> prelevements = PrelevementServiceImpl.getInstance().findAllByidPersonne(idPersonne);
		for (Prelevement prelevement : prelevements) {
			String chaine = "";
			List<Analyse> analyses = AnalyseServiceImpl.getInstance().findAllByidPrelevement(prelevement.getIdPrelevement());
			for (Analyse analyse : analyses) {
				chaine = "Analyse : " + analyse.getTypeAnalyse().getLibelle() + " n°" + analyse.getIdAnalyse() + " du prélèvement : " + prelevement.getNumeroPrelevement();
				liste.add(chaine);
			}
			chaine = "Prélèvement : " + prelevement.getNumeroPrelevement();
			liste.add(chaine);
		}
		listeCombo = new String[liste.size()];
		this.editor = new ComboBoxCellEditor(viewer.getTable(), liste.toArray(listeCombo), SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
	}

	@Override
	protected CellEditor getCellEditor(Object element) {
		return editor;
	}

	@Override
	protected boolean canEdit(Object element) {
		return true;
	}

	@Override
	protected Object getValue(Object element) {
		return 0;
	}

	@Override
	protected void setValue(Object element, Object value) {
		if ((element instanceof Cotation) && (value instanceof Integer)) {
			String chaine = listeCombo[(Integer) value];
			int inum = chaine.indexOf(" n°");
			int idu = chaine.indexOf(" du ");
			int iPrel = chaine.indexOf("rélèvement : ");

			if (inum > 0) {
				String numeroAnalyse = chaine.substring(inum + 3, idu).trim();
				((Cotation) element).setAnalyse(AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(Integer.parseInt(numeroAnalyse)));
			} else {
				((Cotation) element).setAnalyse(null);
			}
			if (iPrel > 0) {
				String numeroPrelevement = chaine.substring(iPrel + 13).trim();
				((Cotation) element).setPrelevement(PrelevementServiceImpl.getInstance().getPrelevementByNumero(numeroPrelevement));
			}

		}
		viewer.update(element, null);
	}

}